<?php

namespace Acme\CommonBundle\EventListener;

use Doctrine\ORM\Event\OnFlushEventArgs;

use Acme\UserBundle\Entity\CmUser;
use Acme\ContestBundle\Entity\CtInfo;

class Logger
{	
	protected $session;
		
	public function __construct($session)
	{
		$this->session = $session;
	}
	
	public function onFlush(OnFlushEventArgs $eventArgs)
	{
		$em = $eventArgs->getEntityManager();
		$uow = $em->getUnitOfWork();
		
		if (unserialize($this->session->get('_security_secured_area'))) {
			$_security_secured_area = unserialize($this->session->get('_security_secured_area'));
			$user = $_security_secured_area->getUser();
			
			foreach ($_security_secured_area->getRoles() as $v) {
				$role = $v->getRole();
			}
			
			if ($role == 'ROLE_SUPER_ADMIN') {
				$user_session_id = 0;
			} else {
				$user_session_id = $user->getId();
			}
		}
		
		foreach ($uow->getScheduledEntityInsertions() as $entity) {
			if ($entity instanceof CmUser) {
				if (isset($user_session_id)) {
					$entity->setCreatedBy($user_session_id);
					$classMetadata = $em->getClassMetadata(get_class($entity));
					$uow->recomputeSingleEntityChangeSet($classMetadata, $entity);
				}
			}
			
			if ($entity instanceof CtInfo) {
				if (isset($user_session_id)) {
					$entity->setCreatedBy($user_session_id);
					
					if ($role == 'ROLE_TEACHER') {
						$entity->setApplyTime(new \DateTime());
					}
					$classMetadata = $em->getClassMetadata(get_class($entity));
					$uow->recomputeSingleEntityChangeSet($classMetadata, $entity);
				}
			}
		}
		
		foreach ($uow->getScheduledEntityUpdates() as $entity) {
			if ($entity instanceof CmUser) {
				if (key_exists('userStatus', $uow->getEntityChangeSet($entity))) {
					$entity->setApprover($user_session_id);
					$entity->setApproveTime(new \DateTime());
					$entity->setModifiedBy($user_session_id);
				} elseif (key_exists('emailStatus', $uow->getEntityChangeSet($entity))) {
					$entity->setModifiedBy((isset($user_session_id)) ? $user_session_id : $entity->getId());
				} elseif (key_exists('flag', $uow->getEntityChangeSet($entity))) {
					$entity->setModifiedBy($user_session_id);
				}
			}
			
			if ($entity instanceof CtInfo) {
				$propertyToSetModifiedBy = array(
						'name', 'contestType', 'isVisiable', 'applyReason',
						'enrollStart', 'enrollEnd', 'contestStart', 'contestEnd',
						'reviewType', 'reviewStart', 'reviewEnd', 'instruction', 'flag');
				
				if (array_diff($propertyToSetModifiedBy, $uow->getEntityChangeSet($entity)) != $propertyToSetModifiedBy) {
					$entity->setModifiedBy($user_session_id);
				} elseif (key_exists('applyState', $uow->getEntityChangeSet($entity))) {
					$entity->setApprover($user_session_id);
					$entity->setApproveTime(new \DateTime());
					$entity->setModifiedBy($user_session_id);
				}
			}
		}
	}
}